#include "lib.hpp"
#include "log.hpp"

int main(int argc, char* argv[])
{
    if (argc != 2) {
        usage(argv[0]);
        exit(1);
    }
    
    struct protoent* protocol = nullptr;
    struct hostent* host = nullptr;
    char dest_addr[ADDR_SIZE];
    memset(dest_addr, 0, sizeof dest_addr);
    uint32_t inaddr = 1;
    pthread_t send_id,recv_id;

    if(!(protocol = getprotobyname("icmp")))
    {
        logMessage(ERROR, "Fail to getprotobyname! %d: %s\n", errno, strerror(errno));
        exit(-1);
    }

    memcpy(dest_addr, argv[1], strlen(argv[1])+1);

    if((sock = socket(AF_INET,SOCK_RAW,protocol->p_proto)) < 0)
    {
        logMessage(ERROR, "Fail to socket! %d: %s\n", errno, strerror(errno));
        exit(-1);
    }

    pid = getpid();        
    int size = 128 * 0x400;
    setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &size, sizeof size); 

    bzero(&dest,sizeof dest);

    dest.sin_family = AF_INET;

    if((inaddr = inet_addr(argv[1])) = INADDR_NONE) {
        host = gethostbyname(argv[1]);
        if(!(host =gethostbyname(argv[1])))
        {
            logMessage(ERROR, "Fail to gethostbyname! %d: %s\n", errno, strerror(errno));
            exit(-1);
        }
        memcpy((char*)&dest.sin_addr, host->h_addr, host->h_length);
    } else {
        memcpy((char*)&dest.sin_addr, &inaddr, sizeof inaddr);
    }
    inaddr = dest.sin_addr.s_addr;
    printf("PING %s, (%d.%d.%d.%d) 56(84) bytes of data.\n",dest_addr, (inaddr & 0xff), (inaddr & 0xff00) >> 8, (inaddr & 0xff0000) >> 0x10, (inaddr & 0xff000000) >> 0x18);

    alive = 1;

    signal(SIGINT, getTime);

    if(pthread_create(&send_id, nullptr, (void*)sendPing, nullptr)) {
        printf("Fail to create ping send thread!\n");
        return -1;
    }

    if(pthread_create(&recv_id, nullptr, (void*)recvPing, nullptr)) {
        printf("Fail to create ping recv thread!\n");
        return -1;
    }

    pthread_join(send_id, nullptr);
    pthread_join(recv_id, nullptr);

    show();

    close(sock);

    return 0;
}
